<template>
  <div class="content-page">
    <div class="header flex justify-between items-center mb-8">
      <div class="search-filter-container flex items-center space-x-4">
        <input type="text" placeholder="搜索证书..." class="search-input border border-gray-300 rounded-md px-3 
        py-2 focus:outline-none focus:ring-blue-500 focus:border-blue-500" />
        <select class="filter-select border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
          <option value="all">全部类型</option>
          <!-- 这里可以添加更多筛选选项 -->
        </select>
        <button class="filter-button bg-blue-500 text-white rounded-md px-2 py-2 hover:bg-blue-600 focus:outline-none
         focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 ">筛选</button>
      </div>
      <!-- <h1 class="text-2xl font-semibold">实习信息页面</h1> -->
      <el-button type="primary" @click="showDialog = true">上传认证</el-button>
    </div>

    <div class="certificate-gallery">
      <div class="certificate-container" v-for="(certificate, index) in certificates" :key="index">
        <h3>{{ certificate.name }}</h3>
        <img :src="certificate.internshipPhoto" :alt="`Certificate Image ${index + 1}`" style="width: 350px;height:250px">
        <div class="certificate-info">
          <p><strong>公司规模:</strong> {{ certificate.companyId }}</p>
          <p><strong>实习岗位:</strong> {{ certificate.position }}</p>
          <p><strong>开始时间:</strong> {{ formatDate(certificate.internshipStarttime) }}</p>
          <p><strong>结束时间:</strong> {{ formatDate(certificate.internshipEndtime) }}</p>
          <p><strong>实习成果:</strong> {{ certificate.internshipSuccess }}</p>
        </div>
        <!-- 状态显示和操作按钮 -->
        <div class="actions-container">
          <!-- 状态显示 -->
          <template v-if="certificate.status === 0">
            <span class="flex items-center gap-1 text-orange-500">
              <i class="fas fa-clock"></i>
              <span class="text-sm">待审核</span>
            </span>
          </template>
          <template v-if="certificate.status === 1">
            <span class="flex items-center gap-1 text-green-600">
              <i class="iconfont icon-gou1"></i>
              <span class="text-sm">审核通过</span>
            </span>
          </template>
          <template v-if="certificate.status === 2">
            <span class="flex items-center gap-1 text-red-600">
              <i class="iconfont icon-chacha"></i>
              <span class="text-sm">审核未通过</span>
            </span>
          </template>

          <!-- 操作按钮 -->
          <button class="edit-button" @click="showEditDialog(certificate)">修改</button>
          <button class="delete-button" @click="confirmRemoveCertificate(certificate.id)">删除</button>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="showDialog">
      <div class="dialog-header mb-6">
        <h2 class="text-xl font-medium">提交实习信息</h2>
      </div>

      <div class="dialog-body">
        <form @submit.prevent="handleSubmit">
          <!-- 表单内容保持不变 -->
          <div class="form-item mb-4">
            <label class="required-label block mb-2">实习公司名:</label>
            <el-select v-model="formData.companyId" placeholder="请选择实习公司" class="w-full text-sm">
              <el-option v-for="(company, index) in companyList" :key="index" :label="company.companyName"
                :value="company.companyName" />
            </el-select>
          </div>

          <div class="form-item mb-4">
            <label class="required-label block mb-2">实习岗位:</label>
            <el-select v-model="formData.position" placeholder="请选择担任岗位" class="w-full text-sm">
              <el-option v-for="(job, index) in jobList" :key="index" :label="job.jobName" :value="job.jobName" />
            </el-select>
          </div>

          <div class="form-item mb-4">
            <label class="required-label block mb-2">实习时间:</label>
            <div class="flex items-center gap-4">
              <el-date-picker v-model="formData.internshipStarttime" type="date" placeholder="选择开始时间"
                class="flex-1 text-sm" />
              <span class="text-gray-400">-</span>
              <el-date-picker v-model="formData.internshipEndtime" type="date" placeholder="选择结束时间"
                class="flex-1 text-sm" />
            </div>
          </div>

          <div class="form-item mb-4">
            <label class="required-label block mb-2">实习成果描述:</label>
            <el-input v-model="formData.internshipSuccess" type="textarea" :maxlength="50" :rows="4"
              placeholder="请输入实习成果证明" show-word-limit class="w-full text-sm" />
          </div>

          <div class="form-item mb-6">
            <label class="required-label block mb-2">图片证明材料:</label>
            <div
              class="upload-area border-2 border-dashed border-gray-200 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400 transition-colors"
              @click="triggerUpload">
              <el-icon class="text-gray-400 text-2xl mb-2">
                <Plus />
              </el-icon>
              <input ref="fileInput" type="file" class="hidden" accept="image/*" @change="handleFileChange">
              <div class="text-gray-500 text-sm">点击或拖拽上传图片(图片需要重新上传)</div>
              <div class="text-gray-400 text-xs mt-1">图片尺寸规则:A4纸为准,大小不大于1M</div>
            </div>
            <!-- 预览区域 -->
            <div v-if="imagePreview" class="mt-4">
              <img :src="imagePreview" alt="预览图片" class="w-full h-auto rounded-lg" />
            </div>
          </div>

          <div class="dialog-footer flex justify-end gap-4">
            <el-button @click="handleCancel" class="!rounded-button whitespace-nowrap">返回</el-button>
            <el-button type="primary" @click="handleSubmit" :disabled="!isFormValid"
              class="!rounded-button whitespace-nowrap">
              提交
            </el-button>
          </div>
        </form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getInternship, deleteInternship, getCompanyList } from '@/api/student/certification/stuInternship';
import { getJobList } from '@/api/student/certification/stuProject';
import { getToken } from '@/utils/auth';
import axios from 'axios';

const imagePreview = ref(null);
const showDialog = ref(false);
const fileInput = ref(null);

// 日期格式化方法
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};

// 确保 formData 的每个字段都被初始化
const formData = ref({
  id: '',
  companyId: '',
  position: '',
  internshipStarttime: '',
  internshipEndtime: '',
  internshipSuccess: '',
  file: null
});
const isFormValid = computed(() => {
  return formData.value.companyId !== '' &&
    formData.value.position !== '' &&
    formData.value.internshipStarttime !== '' &&
    formData.value.internshipEndtime !== '' &&
    formData.value.internshipSuccess !== '' &&
    formData.value.file;
});
const triggerUpload = () => {
  fileInput.value?.click();
};
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    formData.value.file = file;
    if (file.size > 1024 * 1024) {
      ElMessage.error('文件大小不能超过1M');
      formData.value.file = null;
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};
const handleSubmit = async () => {
  if (!isFormValid.value) {
    ElMessage.warning('请填写完整所有必填项');
    return;
  }

  const form = new FormData();
  form.append('images', formData.value.file);
  form.append('internshipExperienceDto', JSON.stringify({
    id: formData.value.id,
    companyId: formData.value.companyId,
    position: formData.value.position,
    internshipStarttime: formData.value.internshipStarttime,
    internshipEndtime: formData.value.internshipEndtime,
    internshipSuccess: formData.value.internshipSuccess,
  }));

  try {
    const token = getToken();
    const response = await axios.post('http://localhost:8081/certificateAuthority/addInternshipExperience', form, {
      headers: {
        'token': `${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 200) {
      ElMessage.success('提交成功');
      formData.value = {
        id: '',
        companyId: '',
        position: '',
        internshipStarttime: '',
        internshipEndtime: '',
        internshipSuccess: '',
        file: null
      };
      imagePreview.value = null;
      showDialog.value = false;
      fetchCertificates();
    } else {
      ElMessage.error(response.data.msg || '提交失败，请稍后重试');
    }
  } catch (error) {
    ElMessage.error('提交时发生错误');
  }
};
const handleCancel = () => {
  showDialog.value = false;
  formData.value = {
    id: '',
    companyId: '',
    position: '',
    internshipStarttime: '',
    internshipEndtime: '',
    internshipSuccess: '',
    file: null
  };
  imagePreview.value = null;
  ElMessage.info('已取消');
};
const certificates = ref([]);
const fetchCertificates = () => {
  getInternship()
    .then(response => {
      certificates.value = response;
    })
    .catch(error => {
      ElMessage.error('查询数据时发生错误');
      console.error(error);
    });
};
onMounted(() => {
  fetchCertificates();
});
function confirmRemoveCertificate(id) {
  ElMessageBox.confirm(
    '您确定要删除这个项目记录吗？此操作不可逆！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    removeCertificate(id);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}
function removeCertificate(id) {
  deleteInternship(id)
    .then(response => {
      ElMessage.success('删除成功');
      fetchCertificates();
    })
    .catch(error => {
      ElMessage.error('删除失败');
      console.error(error);
    });
}
const companyList = ref([]);
const jobList = ref([]);
const loading = ref(false);
watch(showDialog, async (newVal) => {
  if (newVal) {
    try {
      loading.value = true;
      const res = await getJobList();
      const res1 = await getCompanyList();
      jobList.value = res;
      companyList.value = res1;
    } catch (error) {
      ElMessage.error('获取列表失败');
    } finally {
      loading.value = false;
    }
  } else {
    formData.value = {
      id: '',
      companyId: '',
      position: '',
      internshipStarttime: '',
      internshipEndtime: '',
      internshipSuccess: '',
      file: null
    };
  }
});
function showEditDialog(certificate) {
  formData.value = {
    id: certificate.id,
    companyId: certificate.companyId,
    position: certificate.position,
    internshipStarttime: certificate.internshipStarttime,
    internshipEndtime: certificate.internshipEndtime,
    internshipSuccess: certificate.internshipSuccess,
    file: null
  };
  imagePreview.value = certificate.internshipPhoto;
  showDialog.value = true;
}
</script>

<style scoped>
/* .content-page{
  background-color: #101010;
} */
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.dialog-overlay {
  z-index: 1000;
}

.dialog-content {
  width: 90vw;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  background: #fff;
  border-radius: 1rem 0 0 1rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-content::-webkit-scrollbar {
  width: 8px;
}

.dialog-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 1rem;
}

.dialog-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 1rem;
}

.dialog-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.certificate-gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
  justify-items: center;
}

.certificate-container {
  position: relative;
  border-radius: 1rem;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 0.5rem;
  text-align: center;
  width: 400px;
  /* max-width: 300px; */
}

h3 {
  font-size: 1.25rem;
  color: #333;
}

img {
  display: block;
  margin: 0.3rem auto;
  border-radius: 0.5rem;
  width: 400px;
  height: 250px;
}

.certificate-info {
  text-align: left;
  margin-top: 0.5rem;
  overflow-wrap: break-word;
  word-break: break-all;
  max-width: 260px;
}

p {
  font-size: 1rem;
  color: #00796b;
  margin: 0.3rem 0;
}

.actions-container {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  margin-top: 0.5rem;
  justify-content: flex-end;
}

.edit-button {
  background-color: #2196f3;
  color: white;
  border: none;
  padding: 0.3rem 0.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
  margin-right: 0.3rem;
}

.edit-button:hover {
  background-color: #1976d2;
}

.delete-button {
  background-color: red;
  color: white;
  border: none;
  padding: 0.3rem 0.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
}

.delete-button:hover {
  background-color: darkred;
}

.search-input {
  width: 80%;
  max-width: 400px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px 12px;
}

.search-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
  border-color: #3b82f6;
}

.filter-select {
  width: auto;
  min-width: 150px;
  padding: 0.5rem 0.75rem; /* 调整内边距，确保和输入框、按钮高度一致 */
  line-height: 1.25; /* 调整行高，确保文字垂直居中 */
}

.filter-button {
  width: auto;
  min-width: 80px;
  padding: 0.5rem 1rem; /* 调整内边距，确保和输入框、选择框高度一致 */
  line-height: 1.25; /* 调整行高，确保文字垂直居中 */
}

.upload-area {
  transition: border-color 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: scale(1.05);
}
.certificate-info p {
  font-size: 1rem;
  color: #000; /* 原来为#00796b，现改为黑色#000 */
  margin: 0.15rem 0;
  white-space: nowrap; 
  overflow: hidden; 
  text-overflow: ellipsis; 
}

</style>